import React, { useState, useRef, useEffect } from "react";
import { Modal, Form, Input, Spin } from "antd";

const AddJob = ({ job, open, onOk, onCancel }) => {
  // 克隆部门信息
  const [addingJob, setAddingJob] = useState({ ...job });
  const [loading, setLoading] = useState(false);
  const [key, setKey] = useState(Math.random());
  useEffect(() => {
    setAddingJob({ ...job });
    setKey(Math.random());
  }, [job]);
  const myRef = useRef(null); // 创建 ref
  return (
    <Modal
      key={key}
      title="新增职位"
      cancelText="取消"
      okText="确定"
      open={open}
      destroyOnClose={true}
      onOk={() => {
        myRef.current.click();
      }}
      onCancel={() => {
        onCancel();
      }}
    >
      <Spin
        spinning={loading}
        size="large"
        tip="正在提交..."
        fullscreen={true}
      ></Spin>
      <Form
        onFinish={async () => {
          setLoading(true);
          await onOk(addingJob);
          setLoading(false);
        }}
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 14,
        }}
        layout="horizontal"
        initialValues={{
          name: "",
          explain: "",
        }}
        preserve={false}
      >
        <Form.Item
          label="名称"
          name="name"
          rules={[
            {
              required: true,
              message: "请输入职位名称",
            },
          ]}
        >
          <Input
            value={addingJob.name}
            onChange={(e) =>
              setAddingJob({ ...addingJob, name: e.target.value })
            }
          />
        </Form.Item>
        <Form.Item
          label="描述"
          name="explain"
          rules={[
            {
              required: true,
              message: "请输入职位描述",
            },
          ]}
        >
          <Input.TextArea
            rows={4}
            value={addingJob.explain}
            onChange={(e) =>
              setAddingJob({ ...addingJob, explain: e.target.value })
            }
          />
        </Form.Item>
        <Form.Item>
          <button
            type="submmit"
            ref={myRef}
            style={{ display: "none" }}
          ></button>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddJob;
